$(function() {

    'use strict';

    // var debugBar = {

    //     _MAX   : 40,
    //     _total : 0,

    //     _elTpl : '<div>' +
    //                '<div id="debug_bar_content" style="display:none;position:fixed;z-index:9999999;height:200px;left:0;right:0;top:0;background:rgba(0,0,0,0.4);">' +
    //                  '<ul id="debug_bar_list" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow-x:hidden;overflow-y:scroll">' +
    //                  '</ul>' +
    //                  '<div id="debug_bar_prev_btn" style="position:absolute;width:50px;height:50px;right:0;top:100px;background:rgba(0,0,0,0.01"></div>' +
    //                  '<div id="debug_bar_next_btn" style="position:absolute;width:50px;height:50px;right:0;top:150px;background:rgba(0,0,0,0.01"></div>' +
    //                  '<div id="debug_bar_close_btn" style="position:absolute;width:50px;height:50px;right:0;top:0px;background:rgba(0,0,0,0.01"></div>' +
    //                '</div>' +
    //                '<div id="debug_bar_title" style="position:fixed;z-index:9999999;height:20px;left:0;top:0;right:0;padding:0 10px;line-height:20px;font-size:12px;color:#fff;text-align:left;background:rgba(0,0,0,0.75);"></div>' +
    //              '</div>',

    //     _itemTpl : '<li style="position:relative;height:19px;margin:0;margin-bottom:1px;padding:0 10px;line-height:19px;font-size:12px;color:#fff;text-align:left;background:rgba(0,0,0,0.3);"></li>',

    //     show : function(msg) {

    //         var el = $(this._itemTpl).html(msg),
    //             sTop = this._listEl.scrollTop();

    //         this._titleEl.html(msg);
    //         this._listEl.append(el);
    //         this._listEl.scrollTop(sTop + 20);

    //         if (++this._total > this._MAX) {
    //             $('#debug_bar_list li').eq(0).remove();
    //         }

    //         return this;
    //     },

    //     init: function() {

    //         var el = $(this._elTpl),
    //             title    = el.find('#debug_bar_title'),
    //             content  = el.find('#debug_bar_content'),
    //             list     = el.find('#debug_bar_list'),
    //             closeBtn = el.find('#debug_bar_close_btn'),
    //             prevBtn  = el.find('#debug_bar_prev_btn'),
    //             nextBtn  = el.find('#debug_bar_next_btn');

    //         this._titleEl = title;
    //         this._listEl  = list;

    //         $('body').append(el);

    //         title.bind('touchstart', function() {
    //             title.hide();
    //             content.show();
    //             return false;
    //         });

    //         closeBtn.bind('touchstart', function() {
    //             title.show();
    //             content.hide();
    //             return false;
    //         });

    //         prevBtn.bind('touchstart', function() {
    //             var sTop = list.scrollTop();
    //             list.scrollTop(sTop - 20);
    //             return false;
    //         });
    //         nextBtn.bind('touchstart', function() {
    //             var sTop = list.scrollTop();
    //             list.scrollTop(sTop + 20);
    //             return false;
    //         });

    //         return this;
    //     }
    // };

    var shareSDK = {

        _info : {
            shareTitle     : '管不住嘴又想减肥的必看！',
            descContent    : '这套专为吃货设计的瘦身操，一开始我是不信的',
            shareTimeTitle : '这套专为吃货设计的瘦身操，一开始我是不信的',
            imgUrl         : __CDNPATH + '/data/share.jpg',
            lineLink       : window.location.href
        },

        _doneAppCbk: function() {
            nie.config.stats.url.add('gfxm1_chihuo_20150820.html?click=share', '分享给好友');
        },

        _doneTimelineCbk: function() {
            nie.config.stats.url.add('gfxm1_chihuo_20150820.html?click=share', '分享到朋友圈');
        },

        set: function(info) {

            var that = this;

            if (info) {
                info.shareTitle     && (this._info.shareTitle     = info.shareTitle    );
                info.descContent    && (this._info.descContent    = info.descContent   );
                info.shareTimeTitle && (this._info.shareTimeTitle = info.shareTimeTitle);
            }

            wx.ready(function() {
                wx.onMenuShareTimeline({
                    title   : that._info.shareTimeTitle,
                    link    : that._info.lineLink,
                    imgUrl  : that._info.imgUrl,
                    success : that._doneTimelineCbk
                });
                wx.onMenuShareAppMessage({
                    title   : that._info.shareTitle,
                    desc    : that._info.descContent,
                    link    : that._info.lineLink,
                    imgUrl  : that._info.imgUrl,
                    success : that._doneAppCbk
                });
            });

            return this;
        },

        init: function() {

            var that = this;

            document.addEventListener('YixinJSBridgeReady', function() {
                YixinJSBridge.on('menu:share:appmessage', function() {
                    YixinJSBridge.invoke('sendAppMessage', {
                      img_width  : '300',
                      img_height : '300',
                      img_url    : that._info.imgUrl,
                      link       : that._info.lineLink,
                      desc       : that._info.descContent,
                      title      : that._info.shareTitle
                    }, that._doneAppCbk);
                });
                YixinJSBridge.on('menu:share:timeline', function() {
                    YixinJSBridge.invoke('shareTimeline', {
                      img_width  : '300',
                      img_height : '300',
                      img_url    : that._info.imgUrl,
                      link       : that._info.lineLink,
                      desc       : that._info.shareTimeTitle,
                      title      : that._info.shareTimeTitle
                    }, that._doneTimelineCbk);
                });
            }, false);

            wx.config(wx_conf);

            this.set();

            return this;
        }
    };

    var imgLoader = {

        _srcs      : [],
        _onLoaded  : null,
        _onLoading : null,

        load: function() {

            var srcs      = this._srcs,
                l         = srcs.length,
                loadCount = 0,
                that      = this,
                tmp,
                i;

            function onImgLoad() {
                if (++loadCount === l) {
                    that._onLoaded && that._onLoaded();
                } else {
                    that._onLoading && that._onLoading(Math.floor(loadCount / l * 100));
                }
            }

            if (!l) {
                that._onLoaded && that._onLoaded();
                return this;
            }

            for (i = l; i--;) {
                tmp        = new Image();
                tmp.src    = srcs[i];
                tmp.onload = onImgLoad;
            }

            return this;
        },

        init: function(arrSrcs, onLoaded, onLoading) {

            this._srcs      = arrSrcs.slice(0);
            this._onLoaded  = onLoaded;
            this._onLoading = onLoading;

            return this;
        }
    };

    var motion = {

        _biPath: [function(x, y, z) {
            if (Math.abs(x) < 3 &&
                    Math.abs(y) < 7 &&
                    Math.abs(y) > 3 &&
                    Math.abs(z) < 5 ) {
                return true;
            } else {
                return false;
            }
        }, function(x, y, z) {
            if (Math.abs(x) < 9 &&
                    Math.abs(x) > 3 &&
                    Math.abs(y) < 6 &&
                    Math.abs(y) > 1 &&
                    Math.abs(z) < 7 &&
                    Math.abs(z) > 3 ) {
                return true;
            } else {
                return false;
            }
        }],

        _yaoPath: [function(x, y, z) {
            if (Math.abs(x) < 5 && Math.abs(y) < 5 && Math.abs(z) > 5) {
                return true;
            } else {
                return false;
            }
        }, function(x, y, z) {
            if (Math.abs(x) > 5 && Math.abs(y) < 5 && Math.abs(z) < 5) {
                return true;
            } else {
                return false;
            }
        }, function(x, y, z) {
            if (Math.abs(x) < 5 && Math.abs(y) < 5 && Math.abs(z) > 5) {
                return true;
            } else {
                return false;
            }
        }],

        _tuiPath: [function(x, y, z) {
            if (Math.abs(z) < 4) {
                return true;
            } else {
                return false;
            }
        }, function(x, y, z) {
            if (Math.abs(x) < 4 && Math.abs(y) < 4 && Math.abs(z) > 6) {
                return true;
            } else {
                return false;
            }
        }],

        oneBi: function(callback) {
            return this._listenPath(this._biPath, callback);
        },

        oneYao: function(callback) {
            return this._listenPath(this._yaoPath, callback);
        },

        oneTui: function(callback) {
            return this._listenPath(this._tuiPath, callback);
        },

        stopListening: function() {
            window.removeEventListener('devicemotion', this._onMotion);
            return this;
        },

        _listenPath: function(pathArr, callback) {

            var funcArr  = pathArr.slice(),
                currFunc = funcArr.shift(),
                x,
                y,
                z;

            var onDone = function() {
                window.removeEventListener('devicemotion', onMotion);
                callback && callback();
            };

            var onMotion = this._onMotion = function(event) {

                x = event.accelerationIncludingGravity.x;
                y = event.accelerationIncludingGravity.y;
                z = event.accelerationIncludingGravity.z;

                // debugBar.show(x + ' ' + y + ' ' + z);

                if (currFunc(x, y, z)) {
                    currFunc = funcArr.shift();
                    if (!currFunc) { onDone(); }
                }
            };

            if (window.DeviceMotionEvent) {
                window.addEventListener('devicemotion', onMotion, false);
            } else {
                onDone();
            }


            return this;
        },

        oneShake: function(callback) {

            var SHAKE_THRESHOLD = 100,
                lastX = 0,
                lastY = 0,
                lastZ = 0,
                x     = 0,
                y     = 0,
                z     = 0,
                count = 30,
                lastTime,
                now,
                speed;

            var onDone = function() {
                window.removeEventListener('devicemotion', onMotion);
                callback && callback();
            };

            var onMotion = function(event) {

                x = event.accelerationIncludingGravity.x;
                y = event.accelerationIncludingGravity.y;
                z = event.accelerationIncludingGravity.z;

                now = new Date().getTime();

                if (lastTime) {
                    speed = Math.abs(x + y + z - lastX - lastY - lastZ) /
                            (now - lastTime) * 1000;

                    if (speed > SHAKE_THRESHOLD && count-- <= 0) {
                        onDone();
                    }
                }

                lastX    = x;
                lastY    = y;
                lastZ    = z;
                lastTime = now;
            };

            if (window.DeviceMotionEvent) {
                window.addEventListener('devicemotion', onMotion, false);
            } else {
                onDone();
            }

            return this;
        }
    };

    var homePage = {

        init: function() {

            $('.page-home .enter-btn').click(function() {
                $('.page-home, .page-confirm').remove();
                return false;
            });

            $('.page-home .confirm-btn').click(function() {
                $('.page-home').remove();
                return false;
            });

            return this;
        }
    };

    var confirmPage = {

        init: function() {

            $('.page-confirm .enter-btn').click(function() {
                $('.page-confirm').remove();
                return false;
            });

            return this;
        }
    };

    var enterPage = {

        init: function() {

            $('.page-enter .select-btn').click(function() {
                $('.pop-enter').fadeIn();
                return false;
            });

            return this;
        }
    };

    var selectPage = {

        init: function() {

            $('.page-select .btn').click(function() {
                actionPage.reset($(this).data('type'))
                        .start($(this).data('action'));
                $('.page-select').hide();
                return false;
            });

            return this;
        }
    };

    var actionPage = {

        _curr : 0,

        _onOneDone: function(name) {

            var that = this;

            $('#audio_sound')[0].play();

            if (++this._curr < 3) {
                $('.page-action .act-btn' + this._curr).addClass('active');
                motion[name](function() {
                    that._onOneDone(name);
                });
            } else {
                $('.page-action .act-btn' + this._curr).addClass('active');
                this._doneCbk && this._doneCbk();
            }

            return this;
        },

        start: function(name) {

            var that = this;

            motion[name](function() {
                that._onOneDone(name);
            });

            return this;
        },

        reset: function(type) {
            this._curr = 0;
            $('.page-action .act-btn').removeClass('active');
            $('.page-action .show').attr('class', 'show').addClass('type' + type);
            return this;
        },

        init: function() {

            var that = this;

            this._doneCbk = function() {
                $('.pop-lingjiang').fadeIn();
            };

            $('.page-action .back-btn').click(function() {
                $('.page-select').show();
                motion.stopListening();
                return false;
            });

            return false;
        }
    };

    var shakePage = {

        bind: function() {

            motion.oneShake(function() {
                $('.page-shake').remove();
                $('.page-download').addClass('active');
            });

            return this;
        },

        init: function() {
            // Do mothing
            return this;
        }
    };

    var pop = {

        _initEnterPop: function() {

            $('.pop-enter .go-btn').click(function() {
                $('.pop-enter').remove();
                $('.page-enter').remove();
                $('.page-select').addClass('active');
                return false;
            });

            return this;
        },

        _initSentPop: function() {

            $('.pop-sent .go-btn').click(function() {
                $('.pop-sent').remove();
                $('.page-action').remove();
                $('.page-shake').addClass('active');
                shakePage.bind();
                return false;
            });

            return this;
        },

        _initLingjiangPop: function() {

            var busy = false;

            $('.pop-lingjiang .reject-btn').click(function() {
                $('.pop').fadeOut();
                return false;
            });

            $('.pop-lingjiang .get-verify-btn').click(function() {

                var phone = $('.pop-lingjiang .phone-num').val();

                if (!/^1[34578]\d{9}$/.test(phone)) {
                    alert('请输入正确的手机号码');
                    return false;
                }

                if (!busy) {

                    busy = true;

                    $.ajax({
                        url      : 'http://file.mg.163.com/gfxm/kaola/api.php?' +
                                   'action=ticket',
                        dataType : 'jsonp',
                        scriptCharset : 'UTF-8'

                    }).fail(function() {
                        busy = false;
                        alert('网络错误，请重试');

                    }).done(function(resp) {

                        if (+resp.code !== 1) {
                            busy = false;
                            alert(resp.msg);
                        } else {

                            $.ajax({
                                url : 'http://file.mg.163.com/gfxm/kaola/api.php?' +
                                      'action=code&phone=' + phone + '&ticket=' + resp.msg,
                                dataType : 'jsonp',
                                scriptCharset : 'UTF-8'
                            }).fail(function() {
                                busy = false;
                                alert('网络错误，请重试');

                            }).done(function(resp) {

                                busy = false;

                                if (+resp.code !== 1) {
                                    alert(resp.msg);
                                } else {
                                    alert('验证码已发送到手机，请注意查收');
                                }
                            });
                        }
                    });

                }

                return false;
            });

            $('.pop-lingjiang .submit-btn').click(function() {

                var phone = $('.pop-lingjiang .phone-num').val(),
                    verifyCode = $('.pop-lingjiang .verify-code').val();

                if (!/^1[34578]\d{9}$/.test(phone)) {
                    alert('请输入正确的手机号码');

                } else if (!verifyCode) {
                    alert('请输入验证码');

                } else if (busy) {
                    // do nothing
                } else {

                    busy = true;

                    $.ajax({
                        url : 'http://file.mg.163.com/gfxm/kaola/api.php?' +
                              'action=submit&phone=' + phone +
                              '&checkcode=' + verifyCode,
                        dataType : 'jsonp',
                        scriptCharset : 'UTF-8'

                    }).done(function(resp) {

                        busy = false;

                        if (+resp.code !== 1) {
                            alert(resp.msg);
                        } else {
                            $('.pop-lingjiang').hide();
                            $('.pop-sent').show();
                        }

                    }).fail(function() {
                        busy = false;
                        alert('网络错误，请重试');
                    });
                }


                return false;
            });

            return this;
        },

        init: function() {

            $('.pop .close-btn').click(function() {
                $('.pop').fadeOut();
                return false;
            });

            return this._initEnterPop()._initSentPop()._initLingjiangPop();
        }
    };

    shareSDK.init();

    homePage.init();
    confirmPage.init();
    enterPage.init();
    selectPage.init();
    actionPage.init();
    shakePage.init();

    pop.init();

    // debugBar.init();

    // Init
    var loadList = [],
        list = $('#preload_list img');

    for (var i = list.length; i--;) {
        loadList.push(list.eq(i).data('src'));
    }

    imgLoader.init(loadList, function() {

        $('#loading .tip').remove();
        $('#loading').fadeOut(2000, function() {
            $('#loading').remove();
        });

    }, function(pct) {
        $('#loading .tip span').html(pct);
    }).load();

});
